import {
	wxGetToken,
} from '@/common/login.js'
import movablearea1 from '@/components/movablearea1/movablearea1.vue'
export default {
	data() {
		return {
			baseUrl: 'https://www.wx-sleep.cn',
			fwqUrl: 'https://www.wx-sleep.cn/Zimages/',
			newfwqUrl: '/static/Limages/',
			staticUrl: this.$url, //资源地址
			share: {
				title: '邀请好友',
				path: '/pages/index/index',
			},
			Alias: "",
			Avatar: "",
			playlist: [], //用户播放列表
			blist: [], //轮播列表
			navbackcolor: {
				backgroundColor: 'rgba(255,255,255,0)',
			},
			tabs:0,
			clientHeight:0									,//页面可视化高度	
			imageExtensions: ['jpg', 'jpeg', 'gif', 'png'], //图片后缀
			videoExtensions: ['mp4', 'wmv', 'avi', 'mov'], //视频后缀
			movaheightAll:'35vh',							//滑动块高度
			movaTopAll:'0%'									,//滑动块位置
			movableareaShow:false,							//是否显示电话提示滑动块
			
		}
	},
	// 分享页面消息
	onShareAppMessage(res) {
		var user = uni.getStorageSync('userInfo');
		var userId = user.UserId
		let routes = getCurrentPages();
		let curRoute = routes[routes.length - 1].route //获取当前页面路由
		let curParam = routes[routes.length - 1].options; //获取路由参数
		let str = routes[routes.length - 1].$page.fullPath.indexOf("?") == -1 ? "?" : "&"
		if (userId) this.share.path = routes[routes.length - 1].$page.fullPath + str

		// + 'parentId=' + parseInt(userId);

		if (this.share.path.indexOf("pages2/pages/article/article") != -1 && this.share.path.indexOf(
				"pages2/pages/commodity/commodity")) {
			this.share.path += "&yue=1"
		}
		console.log(this.share.path)
		console.log(curRoute, "curRoute")
		return {
			title: this.share.title,
			path: this.share.path,
			success(res) {
				uni.showToast({
					title: '邀请好友'
				})
			},
			fail(res) {
				uni.showToast({
					title: '邀请好友',
					icon: 'none'
				})
			}
		}
	},
	// 分享朋友圈
	onShareTimeline(res) {
		var user = uni.getStorageSync('userInfo');
		var userId = user.UserId
		let routes = getCurrentPages();
		let curRoute = routes[routes.length - 1].route //获取当前页面路由
		let curParam = routes[routes.length - 1].options; //获取路由参数
		let str = routes[routes.length - 1].$page.fullPath.indexOf("?") == -1 ? "?" : "&"
		if (userId) this.share.path = routes[routes.length - 1].$page.fullPath + str
		// + 'parentId=' + parseInt(userId);
		if (this.share.path.indexOf("pages2/pages/article/article") != -1 && this.share.path.indexOf(
				"pages2/pages/commodity/commodity")) {
			this.share.path += "&yue=1"
		}
		console.log(this.share.path)
		console.log(curRoute, "curRoute")
		return {
			title: this.share.title,
			query: this.share.path.substring((this.share.path.indexOf('?') + 1), this.share.path.length)
		}
	},
	onLoad() {
		
	},
	onShow() {
		

	},
	
	onReady(){
		this.getClineHeight()
	},
	components:{
		movablearea1,			//全局滑动模块
	},
	onHide() {},
	watch: {
		
	},
	methods: {
		
		go: function(url) {
			// let to = uni.getStorageSync("token")
			// if (!this.getText(to)) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '你还没有登录',
			// 		confirmText: "去登录",
			// 		cancelText: "再逛逛",
			// 		success: function(res) {

			// 			if (res.confirm) {
			// 				uni.navigateTo({
			// 					url: '/pages2/pages/login/login'
			// 				});
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消');
			// 			}
			// 		}
			// 	});
			// } else {

			// uni.navigateTo({
			// 	url: url
			// })
			var that = this
			// var newarr = ['/pages2/pages/details/details	','/pages4/sousuo/sousuo', '/pages4/index/tianjiayinyue','/pages/issue/issue']
			// if (this.IsYoungsters == 1) {
			// 	this.$u.toast('青少年模式不可使用该功能')
			// } else {
			this.Zthrottle(() => {
				that.gonavigateTo(url)
			}, 1000) //节流
			// }
			// }
		},
		gonavigateTo: function(url) {
			console.log(url, 461)
			uni.navigateTo({
				url: url
			})
		},
		gos: function(url) {
			console.log('进来了')
			uni.switchTab({
				url: url
			})
		},
		// 关闭页面并跳转
		redirectTo(url){
			uni.reLaunch({
				url:url
			})
		},
		// 接口封装
		async getdatas(data, url, load = 1) {
			let that = this
			let res = await that.$request.urlRequest({
				url: url,
				method: "POST",
				data: data
			}, load)
			return res
		},
		async getdatas2(data, url, load = 1) {
			let that = this
			let res = await that.$request.urlRequest({
				url: url,
				method: "GET",
				data: data
			}, load)
			return res
		},
		// 图片预览
		clickImg(index, item) {
			let that = this
			let items = item
			wx.previewImage({
				urls: items, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
				current: items[index], // 当前显示图片的http链接，默认是第一个
				success: function(res) {},
				fail: function(res) {},
				complete: function(res) {
					console.log(res)
				},
			})
		},
		// 富文本转换
		zhua(cen) {
			let richtext = cen;
			const regex = new RegExp('<img', 'gi');
			richtext = richtext.replace(regex, '<img style="max-width: 100%;display:block;"');
			const regex2 = new RegExp('<video', 'gi');
			richtext = richtext.replace(regex2, '<video style="max-width: 100%;"');

			if (richtext.indexOf("http") == -1) {
				const regex2 = new RegExp('src="', 'gi');
				let rs = 'src="' + this.staticUrl
				richtext = richtext.replace(regex2, rs);
			}
			return richtext
		},
		// 图片预览(检测是否为空)
		clickImg2(arr) {
			let that = this
			let arrs = []
			if (!that.getText(arr)) {
				return
			}
			console.log(arr)
			arrs.push(that.getUrl(arr))
			wx.previewImage({
				urls: arrs, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
				success: function(res) {},
				fail: function(res) {},
				complete: function(res) {},
			})
		},
		// 图片预览(字符串转换成数组)
		clickImg3(arr, index) {
			let that = this
			let arrs = []
			if (!that.getText(arr)) {
				return
			}
			arrs = arr.split(',')
			wx.previewImage({
				urls: arrs, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
				success: function(res) {},
				fail: function(res) {},
				complete: function(res) {},
			})
		},
		// 上传文件(反馈上传进度)
		uploading(url, ds) {
			let that = this
			let das = {
				isbaby: this.getText(ds) ? ds.isbaby : 0,
				classId: this.getText(ds) ? ds.classId : 0,
				coverurl: this.getText(ds) ? ds.coverurl : ''
			}

			return new Promise((resolve, reject) => {
				let to = uni.getStorageSync("token")
				let headers = {}
				let data = new Date().getTime()
				headers['Authorization'] = `Bearer ${to}`
				if (url.indexOf("Upload") != -1) {
					resolve(url)
				} else {
					let re;
					uni.showLoading({
						title: "上传视频中..."
					})
					const uploadTask = uni.uploadFile({
						url: that.staticUrl + '/api/Upload/APiUploadFile',
						filePath: url,
						name: 'file',
						header: headers,
						formData: {
							uploadfileNo: data,
							isbaby: das.isbaby,
							classId: das.classId,
							coverurl: das.coverurl
						},
						success: (uploadFileRes) => {
							console.log(uploadFileRes, 358)
							if (uploadFileRes.statusCode != 200) {
								return
							}
							re = JSON.parse(uploadFileRes.data)
							if (re.code != 200) {
								resolve('')
							} else {

								console.log(re, 401)
								re.data = this.getUrl(re.data)
								console.log(re.data)
								console.log(resolve(re.data))
								resolve(re.data)
							}
							uni.hideLoading()
						},
						complete(res) {
							console.log(res)
							uni.hideLoading()
						}
					})
					uploadTask.onProgressUpdate((res) => {
						console.log('上传进度' + res.progress);
						console.log('已经上传的数据长度' + res.totalBytesSent);
						console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
						uni.showLoading({
							title: '上传进度' + res.progress + '%'
						})
						// 测试条件，取消上传任务。
						// if (res.progress > 50) {
						// 	uploadTask.abort();
						// }
					});
				}
			})
		},
		// 选择图片
		upimg(coun) {
			return new Promise((resolve, reject) => {
				uni.chooseImage({
					count: coun, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						resolve(res.tempFilePaths)
					}
				});
			})
		},
		// 版本更新(小程序)
		autoUpdate: function() {
			const updateManager = uni.getUpdateManager();

			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				console.log(res.hasUpdate, "auto");
			});

			updateManager.onUpdateReady(function(res) {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});

			});

			updateManager.onUpdateFailed(function(res) {
				// 新的版本下载失败
			});
		},
		// 加载中(提示)
		pageshowloading() {
			uni.showLoading({
				title: "加载中...",
				mask: true
			})
			setTimeout(function() {
				uni.hideLoading()
			}, 3000);
		},
		// 取消加载中提示
		hide() {
			uni.hideLoading()
		},
		// 支付调用
		pay(res) {
			return new Promise((resolve, reject) => {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: res.data.wxData.timeStamp,
					nonceStr: res.data.wxData.nonceStr,
					package: res.data.wxData.package,
					signType: res.data.wxData.signType,
					paySign: res.data.wxData.paySign,
					success: function(resa) {
						uni.showToast({
							title: '支付成功',
							duration: 1500,
						});
						resolve(1)
					},
					fail: function(err) {
						uni.hideLoading()
						resolve(-1)
					},
					complete() {
						uni.hideLoading()
					}
				});
			})

		},
		// 电话拨打功能
		phon(ph) {
			uni.makePhoneCall({
				phoneNumber: ph //仅为示例
			})
		},
		// 使用微信内置地图查看位置(小程序)
		getMap(lat, log) {
			uni.openLocation({
				latitude: lat,
				longitude: log,
				success: function() {
					console.log('success');
				}
			});
		},
		// 获取当前经纬度(小程序)
		getlos() {
			return new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						uni.chooseLocation({
							longitude: res.longitude,
							latitude: res.latitude,
							success: function(res) {
								console.log('位置名称：' + res.name);
								console.log('详细地址：' + res.address);
								console.log('纬度：' + res.latitude);
								console.log('经度：' + res.longitude);
								resolve(res)
							},
							complete(res) {
								console.log(res)
							}
						});
					},
					complete(res) {
						console.log(res)
					}
				});

			})
		},
		// 获取首页Banner
		async getbanner(type) {
			var that = this
			var data = {
				queryId: type
			}
			const res = await that.getdatas(data, '/api/OtherApi/LoadBannerList')
			if (res.code == 200) {
				console.log(res)
				that.blist = res.data.items
				that.blist.map(item => {
					item.ImgUrl = that.$url + item.ImgUrl
				})
			}
		},
		// 获取路径
		geturls(item) {
			let list = item
			let that = this
			list.map(items => {
				return items = that.getUrl(items)
			})
			return list
		},
		// 提示弹窗
		toast(titl) {
			uni.showToast({
				title: titl,
				icon: "none"
			})
		},
		// 解析路径参数
		getOption(op) {
			let obj = {};
			let arr = op.split('&');
			arr.forEach(item => {
				let param = item.split('=');
				obj[param[0]] = param[1];
			})
			return obj
		},
		// 选择视频
		upVideo() {
			return new Promise((resolve, reject) => {
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					success: function(res) {
						resolve(res.tempFilePath)
					}
				});
			})
		},
		// 页面返回
		Allback() {
			let routes = getCurrentPages();
			if (routes.length == 1) {
				this.gos('/pages/index/index')
			} else {
				uni.navigateBack({
					delta: 1
				})
			}
		},
		//节流
		Zthrottle(fn, delay) {
			// console.log(fn, delay)
			const now = new Date().getTime();
			if (now - this.lastCall < delay) {
				return
			}
			this.lastCall = now
			fn.apply(this, arguments)
		},
		// 防抖
		Zdebounce(fn, delay) {
			clearTimeout(this.timer)
			this.timer = setTimeout(() => {
				fn();
			}, delay);
		},
		getUrl(url) {
			if (url && url != '' && url.indexOf('http') < 0) {

				url = this.staticUrl + url
			}
			return url
		},
		back() {
			let routes = getCurrentPages();
			if (routes.length == 1) {
				this.gos('/pages/index/index')
			} else {
				uni.navigateBack({
					delta: 1
				})
			}
		},
		//获取可视区域高度
		getClineHeight(){
			const res = uni.getSystemInfo({
				success:(res=>{
					this.clientHeight =  res.windowHeight-uni.upx2px(80)-this.getBarHeight();
					// console.log('getBarHeight',this.getBarHeight())
				})
			});
		},
		getBarHeight(){
				const res = uni.getSystemInfoSync()
				// console.log('res',res)
				if(res.osName==='ios'){
					return 44+res.statusBarHeight
				}else if(res.osName==='android'){
					return 48+res.statusBarHeight
				}else{
					return 0;
				}
		},
		// 判断是否图片还是视频
		isImgOfVideo(url) {
			var extension = url.split('.').pop().toLowerCase();
			// console.log('后缀',extension)
			if (this.imageExtensions.includes(extension)) {
				return 'image'
			}
			if (this.videoExtensions.includes(extension)) {
				return 'video'
			}
			return 'image'
		},
		getTimes(t) {
				let h = parseInt(t / 60 / 60 % 24)
				let m = parseInt(t / 60 % 60)
				let s = parseInt(t % 60)
				//三元表达式 补零 如果小于10 则在前边进行补零 如果大于10 则不需要补零
				let data = {
					m: m,
					s: s
				}
				h = h < 10 ? '0' + h : h
				m = m < 10 ? '0' + m : m
				s = s < 10 ? '0' + s : s
	
				return data
			},
		// 修改滑动快高度
		editMovaheightAll(){
			this.movaheightAll = '65vh'
			this.movaTopAll = '50%'
			console.log('被触发了',this.movaheightAll)
		}
	}
}